package com.dmjj.dmjjxt.controller;

import com.dmjj.common.base.BaseController;
import com.dmjj.common.base.LoginEntity;
import com.dmjj.common.fileload.Fileload;
import com.dmjj.common.result.ResultEnum;
import com.dmjj.common.result.ResultObject;
import com.dmjj.common.result.ResultPageObject;
import com.dmjj.common.util.InsertCreatManInfo;
import com.dmjj.common.util.ListCopyToVOUtil;
import com.dmjj.common.vo.ResultPageVO;
import com.dmjj.common.vo.ResultVO;
import com.dmjj.dmjjxt.dto.BrandDTO;
import com.dmjj.dmjjxt.dto.BrandPicDTO;
import com.dmjj.dmjjxt.service.BrandService;
import com.dmjj.dmjjxt.vo.BrandPicVO;
import com.dmjj.dmjjxt.vo.BrandVO;
import com.dmjj.dmjjxtutil.MyProps;
import com.netflix.zuul.context.RequestContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.util.*;

/**
 * @Description 品牌信息表控制器
 * @Author zhangxue
 * @Date 2019-04-11 14:13:52
 */

@RestController
@Api(tags = "品牌信息表控制器")
@RequestMapping("brand")
public class BrandController extends BaseController {

    private static final Log LOGGER = LogFactory.getLog(BrandController.class);

    @Autowired
    private BrandService service;
    @Autowired
    private ResultObject resultObject;
    @Autowired
    private ResultPageObject resultPageObject;
    @Autowired
    private MyProps myProps;

    /**
	 * 品牌信息表列表
     * @Author zhangxue
     * @Date 2019-04-11 14:13:52
	 * @Param
	 * @Return
	 */
    @ApiOperation(value = "品牌信息表列表", response = BrandVO.class)
    @PostMapping("list4Page")
    public ResultPageVO<Object> list4Page(
            BrandVO entity,
            @ApiParam(value = "当前页", required = true) @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @ApiParam(value = "每页显示条数", required = true) @RequestParam(value = "pageSize", defaultValue = "15") Integer pageSize
    ){
        try {
            BrandDTO entityDTO = new BrandDTO();
            BeanUtils.copyProperties(entity, entityDTO);
            entityDTO.setDelstatus("0");
            List<BrandDTO> list = service.list4Page(entityDTO, pageNum, pageSize);
            List<BrandDTO> list1 = service.listByCondition(entityDTO);
            //总条数
            Integer total = list1.size();
            Integer totalPage = total/pageSize;
            if(total%pageSize!=0){
                totalPage += 1;
            }
            Boolean hasNext = false;
            if(pageNum!=null&&pageNum<totalPage){
                hasNext = true;
            }
            return resultPageObject.success(ResultEnum.SUCCESS.getCode(),ResultEnum.SUCCESS.getMsg(),pageNum,totalPage,pageSize,total,hasNext,list);
        }catch (Exception e) {
            e.printStackTrace();
            return resultPageObject.error(ResultEnum.EXCEPTION.getCode(), ResultEnum.EXCEPTION.getMsg());
        }
    }

    /**
     * 品牌信息表列表（无分页）
     * @Author zhangxue
     * @Date 2019-04-11 14:13:52
     * @Param
     * @Return
     */
    @ApiOperation(value = "品牌信息表列表（无分页）", response = BrandVO.class)
    @PostMapping("listByCondition")
    public ResultVO<Object> listByCondition(BrandVO entity){
        try {
            BrandDTO entityDTO = new BrandDTO();
            BeanUtils.copyProperties(entity, entityDTO);
            List<BrandDTO> list = service.listByCondition(entityDTO);
            return resultObject.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), ListCopyToVOUtil.getListToVO(list, BrandVO.class));
        }catch (Exception e) {
            e.printStackTrace();
            return resultObject.error(ResultEnum.EXCEPTION.getCode(), ResultEnum.EXCEPTION.getMsg());
        }
    }

    /**
     * 查询品牌名称、品牌编号
     * @Author zhangxue
     * @Date 2019-04-11 14:13:52
     * @Param
     * @Return
     */
    @ApiOperation(value = "查询品牌名称、品牌编号", response = BrandVO.class)
    @PostMapping("queryAllBrandNameAndNo")
    public ResultVO<Object> queryAllBrandNameAndNo(BrandVO entity){
        try {
            BrandDTO entityDTO = new BrandDTO();
            BeanUtils.copyProperties(entity, entityDTO);
            List<Map<String,Object>> list = service.queryAllBrandNameAndNo(entityDTO);
            return resultObject.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), list);
        }catch (Exception e) {
            e.printStackTrace();
            return resultObject.error(ResultEnum.EXCEPTION.getCode(), ResultEnum.EXCEPTION.getMsg());
        }
    }

    /**
     * 通过品牌编号查询品牌信息
     * @Author zhangxue
     * @Date 2019-04-11 14:13:52
     * @Param
     * @Return
     */
    @ApiOperation(value = "通过品牌编号查询品牌信息", response = BrandVO.class)
    @PostMapping("queryBrandInfoByBrandNo")
    public ResultVO<Object> queryBrandInfoByBrandNo(BrandVO entity){
        try {
            BrandDTO entityDTO = new BrandDTO();
            BeanUtils.copyProperties(entity, entityDTO);
            entityDTO = service.queryBrandInfoByBrandNo(entityDTO);
            return resultObject.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), entityDTO);
        }catch (Exception e) {
            e.printStackTrace();
            return resultObject.error(ResultEnum.EXCEPTION.getCode(), ResultEnum.EXCEPTION.getMsg());
        }
    }

    /**
     * 品牌信息表详细信息
     * @Author zhangxue
     * @Date 2019-04-11 14:13:52
     * @Param
     * @Return
     */
    @ApiOperation(value = "品牌信息表详细信息", response = BrandVO.class)
    @PostMapping("queryOneByPk")
    public ResultVO<Object> queryOneByPk(@ApiParam(value = "id",required = true) @RequestParam(value = "id") Long id){
        try {
            BrandDTO entityDTO = service.queryOneByPk(id);
            BrandVO entity = new BrandVO();
            BeanUtils.copyProperties(entityDTO, entity);
            return resultObject.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), entity);
        }catch (Exception e) {
            e.printStackTrace();
            return resultObject.error(ResultEnum.EXCEPTION.getCode(), ResultEnum.EXCEPTION.getMsg());
        }
    }

    /**
     * 保存品牌信息表信息
     * @Author zhangxue
     * @Date 2019-04-11 14:13:52
     * @Param
     * @Return
     */
    @ApiOperation(value = "保存品牌信息表信息", response = ResultVO.class)
    @PostMapping("save")
    public ResultVO<Object> save(BrandVO entity) {
        try {
            BrandDTO entityDTO = new BrandDTO();
            BeanUtils.copyProperties(entity, entityDTO);
            LoginEntity loginEntity = getUserInfo();
            if(loginEntity==null){
                return resultObject.error(ResultEnum.FAIL.getCode(), "token过期");
            }
            //获取创建人、创建时间
            entityDTO = InsertCreatManInfo.Update(entityDTO,loginEntity);
            List<BrandDTO> SameList = service.queryBrandInfoByName(entityDTO);
            if(SameList.size()>0){
                return resultObject.error(ResultEnum.FAIL.getCode(), "品牌名称重复");
            }
            if(service.save(entityDTO) > 0) {
                return resultObject.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(),entityDTO);
            }else {
                return resultObject.error(ResultEnum.FAIL.getCode(), ResultEnum.FAIL.getMsg());
            }
        }catch (Exception e) {
            e.printStackTrace();
            return resultObject.error(ResultEnum.EXCEPTION.getCode(), ResultEnum.EXCEPTION.getMsg());
        }
    }

    /**
     * 修改品牌信息表信息
     * @Author zhangxue
     * @Date 2019-04-11 14:13:52
     * @Param
     * @Return
     */
    @ApiOperation(value = "修改品牌信息表信息", response = ResultVO.class)
    @PostMapping("update")
    @Transactional
    public ResultVO<Object> update(BrandVO entity) {
        try {
            BrandDTO entityDTO = new BrandDTO();
            BeanUtils.copyProperties(entity, entityDTO);
            LoginEntity loginEntity = getUserInfo();
            if(loginEntity==null){
                return resultObject.error(ResultEnum.FAIL.getCode(), "token过期");
            }
            //获取创建人、创建时间
            entityDTO = InsertCreatManInfo.UpdateUpdate(entityDTO,loginEntity);
            if(service.edit(entityDTO) == 1) {
                return resultObject.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(),entityDTO);
            }else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return resultObject.error(ResultEnum.FAIL.getCode(), ResultEnum.FAIL.getMsg());
            }
        }catch (Exception e) {
            e.printStackTrace();
            return resultObject.error(ResultEnum.EXCEPTION.getCode(), ResultEnum.EXCEPTION.getMsg());
        }
    }

    /**
     * 删除品牌信息表信息
     * @Author zhangxue
     * @Date 2019-04-11 14:13:52
     * @Param
     * @Return
     */
    @ApiOperation(value = "删除品牌信息表信息", response = ResultVO.class)
    @PostMapping("delete")
    public ResultVO<Object> delete(@ApiParam(value = "brandno",required = true) @RequestParam(value = "brandno") String brandno){
        try {
            if(service.deleteBrand(brandno) > 0) {
                return resultObject.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg());
            }else {
                return resultObject.success(ResultEnum.FAIL.getCode(), ResultEnum.FAIL.getMsg());
            }
        }catch (Exception e) {
            e.printStackTrace();
            return resultObject.error(ResultEnum.EXCEPTION.getCode(), ResultEnum.EXCEPTION.getMsg());
        }
    }


    /**
     * @Author zhangxue
     * @Description //TODO 通过品牌编号查询历届合同信息
     * @Date 14:59 2019/4/30
     * @Param
     * @return
     **/
    @ApiOperation(value = "通过品牌编号查询历届合同信息", response = BrandVO.class)
    @PostMapping("queryContractInfoByBrandNo")
    public ResultVO<Object> queryContractInfoByBrandNo(@ApiParam(value = "brandno",required = true) @RequestParam(value = "brandno") String brandno){
        try {
            List<Map<String,Object>> resultList = service.queryContractInfoByBrandNo(brandno);
            return resultObject.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), resultList);
        }catch (Exception e) {
            e.printStackTrace();
            return resultObject.error(ResultEnum.EXCEPTION.getCode(), ResultEnum.EXCEPTION.getMsg());
        }
    }


    @RequestMapping(value="brandUpload",method = RequestMethod.POST)
    @ResponseBody
    public ResultVO<Object>  fileUpload2(@RequestParam(value = "brandno") String brandno,
                                         @RequestParam(value = "pictype") String pictype,
                                         @RequestParam(value = "file") MultipartFile file, HttpServletRequest request){
        String token = null;
        HttpServletRequestWrapper httpServletRequestWrapper = (HttpServletRequestWrapper) request;
        token = httpServletRequestWrapper.getRequest().getParameter("token");
        if(token==null||"".equals(token)){
            return null;
        }
        LoginEntity loginEntity = getUserInfo2(token);
        long  startTime=System.currentTimeMillis();
        String jpgorpng = file.getOriginalFilename();
        System.out.println("fileName："+jpgorpng);
        String jop = jpgorpng.substring(jpgorpng.lastIndexOf('.'));
        String PicFileUrl = System.getProperty("user.dir")+"/static/brandpic";
        String PicPath="/"+pictype+"/"+new Date().getTime()+jop;
        String ResultPath = PicFileUrl + PicPath;
        File newFile = new File(ResultPath);
        //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
        try {
            if (!newFile.getParentFile().exists()) {
                newFile.getParentFile().mkdirs();
            }
            file.transferTo(newFile);
        }catch (Exception e){
            e.printStackTrace();
            return resultObject.error(ResultEnum.FAIL.getCode(), "存入文件失败");
        }
        long endTime=System.currentTimeMillis();
        System.out.println("采用file.Transto的运行时间："+String.valueOf(endTime-startTime)+"ms");

        //将需要的数据存入数据库
        String userno = loginEntity.getUserid()!=null?loginEntity.getUserid():null;
        String username = loginEntity.getName()!=null?loginEntity.getName():null;
        BrandPicDTO brandPicDTO = new BrandPicDTO();
        brandPicDTO.setBrandno(brandno);
        brandPicDTO.setPictype(Integer.valueOf(pictype));
        brandPicDTO.setPicurl(PicPath);
        brandPicDTO.setCreatemanno(userno);
        brandPicDTO.setCreatemanname(username);
        Integer i = service.saveBrandPic(brandPicDTO);
        if(i==1){
            return resultObject.success(ResultEnum.SUCCESS.getCode(), "上传成功",brandPicDTO);
        }else{
            Boolean b = Fileload.deleteFile(ResultPath);
            if(b){
                return resultObject.error(ResultEnum.FAIL.getCode(), "上传失败，删除图片成功，请重试");
            }else{
                return resultObject.error(ResultEnum.FAIL.getCode(), "上传失败，删除图片失败，请重试");
            }
        }
    }
    /**
     * 创建文件顺便创建父目录
     *
     * @param file file类
     */
    private static void createFile(File file) {
        if (file.exists() && file.isFile()) {
            file.delete();
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }
        File parentFile = file.getParentFile();
        if (parentFile.exists()) {
            if (parentFile.isFile()) {
                parentFile.delete();
                parentFile.mkdirs();
            }
        } else {
            parentFile.mkdirs();
        }
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询品牌图片信息
     * @Author zhangxue
     * @Date 2019-04-11 14:13:52
     * @Param
     * @Return
     */
    @ApiOperation(value = "查询品牌图片信息", response = BrandVO.class)
    @PostMapping("queryBrandPicInfo")
    public ResultVO<Object> queryBrandPicInfo(BrandPicVO entity){
        try {
            BrandPicDTO entityDTO = new BrandPicDTO();
            BeanUtils.copyProperties(entity, entityDTO);
            List<BrandPicDTO> list = service.queryBrandPicInfo(entityDTO);
            return resultObject.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), list);
        }catch (Exception e) {
            e.printStackTrace();
            return resultObject.error(ResultEnum.EXCEPTION.getCode(), ResultEnum.EXCEPTION.getMsg());
        }
    }

    /**
     * 查询品牌图片信息
     * @Author zhangxue
     * @Date 2019-04-11 14:13:52
     * @Param
     * @Return
     */
    @ApiOperation(value = "删除品牌图片信息", response = BrandVO.class)
    @PostMapping("deleteBrandPicById")
    public ResultVO<Object> deleteBrandPicById(BrandPicVO entity){
        try {
            BrandPicDTO entityDTO = new BrandPicDTO();
            BeanUtils.copyProperties(entity, entityDTO);
            Integer i = service.deleteBrandPicById(entityDTO);
            if(i>0){
                return resultObject.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg());
            }else{
                return resultObject.error(ResultEnum.FAIL.getCode(), ResultEnum.EXCEPTION.getMsg());
            }
        }catch (Exception e) {
            e.printStackTrace();
            return resultObject.error(ResultEnum.EXCEPTION.getCode(), ResultEnum.EXCEPTION.getMsg());
        }
    }


    /**
     * 创建文件夹顺便创建父目录
     *
     * @param path 文件夹的路径字符串例如d:/fulld/why/ass/a/asd/
     * @return 如果本来就存在或者创建成功，那么就返回true
     */
    public static void mkdirs(String path) {
        mkdirs(new File(path));
    }

    /**
     * 创建文件夹顺便创建父目录
     *
     * @param file file类
     */
    public static void mkdirs(File file) {
        if (file.exists() && file.isDirectory()) {
            return;
        }
        if (file.exists()) {
            file.delete();
            file.mkdirs();
        } else {
            file.mkdirs();
        }
    }
}